package com.mostromas.ess.project.controller;

import com.mostromas.ess.entities.ProjectCardNumber;
import com.mostromas.ess.project.req.ProjectCardNumberREQ;
import com.mostromas.ess.project.service.IProjectCardNumberService;
import com.mostromas.ess.util.base.Result;
import com.mostromas.ess.util.enums.CardNumberEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Api(value = "软件卡密管理接口", description = "提供软件卡密的添加和删除")
@RestController
@RequestMapping("/cardNumber")
public class ProjectCardNumberController {

    @Autowired
    private IProjectCardNumberService projectCardNumberService;

    @PreAuthorize(("hasAuthority('cardNumber:search')"))
    @ApiOperation("根据条件查询卡密列表")
    @PostMapping("/search")
    public Result search(@RequestBody ProjectCardNumberREQ req){
        return projectCardNumberService.queryList(req);
    }

    @PreAuthorize(("hasAuthority('cardNumber:add')"))
    @ApiOperation("批量生成卡密")
    @PostMapping
    public Result save(@RequestBody ProjectCardNumberREQ req){
        List<ProjectCardNumber> list = new ArrayList<>();
        int day = req.getType() == CardNumberEnum.MONTH?30:req.getType() == CardNumberEnum.SEASON?90:req.getType() == CardNumberEnum.YEAR?360:0;
        UUID uuid;
        for (int i=0;i<req.getNumber();i++) {
            uuid = UUID.randomUUID();
            ProjectCardNumber pcn = new ProjectCardNumber();
            pcn.setType(req.getType());
            pcn.setProjectId(req.getProjectId());
            pcn.setDays(day);
            pcn.setCardNumber(uuid.toString().replace("-", ""));
            pcn.setState(false);
            list.add(pcn);
        }
        return projectCardNumberService.saveList(list);
    }

    @PreAuthorize(("hasAuthority('cardNumber:delete')"))
    @ApiOperation("删除卡号信息接口")
    @DeleteMapping
    public Result delete(@RequestBody List<String> list){
        projectCardNumberService.removeByIds(list);
        return Result.ok();
    }
}
